import pyaudio   
import socket
     
UDP_IP = "127.0.0.1"   
UDP_PORT = 8888  
     
FORMAT = pyaudio.paInt16   
CHANNELS = 1   
RATE = 16000     
CHUNK = 512   
   
# 初始化UDP套接字   
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   
# 初始化音频输入流   
p = pyaudio.PyAudio()
   
# 列出所有音频设备，帮助选择正确的输入设备（可以不要）   
print("Available audio devices:")   
for i in range(p.get_device_count()):
    dev = p.get_device_info_by_index(i)
    print(f"{i}: {dev['name']} (输入通道: {dev['maxInputChannels']})")
   
# 手动选择输入设备（这个可以不要）   
input_device_index = int(input("请输入麦克风设备序号: "))
   
# 创建音频输入流   
stream = p.open(
    format=FORMAT,
    channels=CHANNELS,
    rate=RATE,
    input=True,
    input_device_index=input_device_index,#（可以不要）
    frames_per_buffer=CHUNK   
)
   
print("开始实时语音传输...")
   
try:
    while True:
        data = stream.read(CHUNK)
        sock.sendto(data, (UDP_IP, UDP_PORT))   
except KeyboardInterrupt:
    print("停止传输")      
stream.stop_stream()   
stream.close()   
p.terminate()